package com.sdhs.system.syncdata.service.impl;

import cn.hutool.json.JSONUtil;
import com.banboocloud.Codec.BamboocloudFacade;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdhs.common.utils.ConvertUtils;
import com.sdhs.system.syncdata.domain.SyncSysDept;
import com.sdhs.system.syncdata.dto.SysDeptDTO;
import com.sdhs.system.syncdata.mapper.SyncSysDeptMapper;
import com.sdhs.system.syncdata.service.SyncSysDeptService;
import com.sdhs.system.syncdata.service.SyncSysDeptZhuyunService;
import com.sdhs.system.syncdata.util.Result;
import com.sdhs.system.syncdata.util.ResultUser;
import com.sdhs.system.syncdata.util.TextUtil;
import com.sdhs.system.syncdata.util.TransforUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zhangmy
 * @date 2022/9/2016:46
 * @Description:
 */
@Service
@Slf4j
public class SyncSysDeptServiceImpl extends ServiceImpl<SyncSysDeptMapper, SyncSysDept> implements SyncSysDeptService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SyncSysDeptMapper sysDeptMapper;
    @Autowired
    private SyncSysDeptZhuyunService sysDeptZhuyunService;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Object save(SysDeptDTO dto) {
        SyncSysDept sysDept = ConvertUtils.sourceToTarget(dto, SyncSysDept.class);
        String createor = dto.getBimRemoteUser();
        int insert=0;
        String deptName = sysDept.getDeptName();
        String parentId1 = sysDept.getParentId();
        //查询是否存在机构
        QueryWrapper<SyncSysDept> queryWrapper11=new QueryWrapper<>();
        queryWrapper11.eq("parent_id",parentId1);
        queryWrapper11.eq("dept_name",deptName);
        SyncSysDept one1 = this.getOne(queryWrapper11);
        if(one1!=null){
            String sql="update sys_dept set del_flag='0', status='0', update_by = '"+createor+"', update_time = now() where dept_id='"+one1.getDeptId() + "'";
            insert = this.jdbcTemplate.update(sql);
            if(insert==1){
                sysDept.setDeptId(one1.getDeptId());
            }
        }else{
            sysDept.setCreateBy(createor);
            sysDept.setCreateTime(new Date());
            sysDept.setStatus("0");
            String parentId = dto.getParentId();
            if(parentId==null){
                parentId="0";
                sysDept.setParentId(parentId);
            }
            String sql=" insert into sys_dept " +
                    "        (dept_id,parent_id,dept_name,order_num,status,del_flag,create_by,create_time) " +
                    "values (?,?,?,?,?,?,?,?)";
            try {
                //添加
                insert = jdbcTemplate.update(sql, sysDept.getDeptId(), sysDept.getParentId(), sysDept.getDeptName(), sysDept.getOrderNum(),"0", "0", createor, new Date());
            } catch (DataAccessException e) {
                throw new RuntimeException(e);
            }
            QueryWrapper<SyncSysDept> queryWrapper111=new QueryWrapper<>();
            queryWrapper111.eq("parent_id",sysDept.getParentId());
            queryWrapper111.eq("dept_name",sysDept.getDeptName());
            queryWrapper111.eq("status","0");
            queryWrapper111.eq("del_flag","0");
            SyncSysDept one = this.getOne(queryWrapper111);
            if(one!=null){
               sysDept.setDeptId(one.getDeptId());
            }
            //先添加再修改pids,fullname
            QueryWrapper<SyncSysDept> queryWrapper = new QueryWrapper<>();

            String pid = sysDept.getParentId();
            if(pid!="0"){
                queryWrapper.eq("dept_id", pid);
                SyncSysDept sysDeptP = sysDeptMapper.selectOne(queryWrapper);
                String pids = "";
                String fullName = "";
                if (sysDeptP != null) {
                    String ancestors = sysDeptP.getAncestors();
//                    if("0".equals(ancestors)){
//                        pids=String.valueOf(pid);
//                    }else{
                        pids = sysDeptP.getAncestors() + "," + pid;
//                    }
                    fullName = sysDeptP.getFullName() + "/" + sysDept.getDeptName();
                }
                sysDeptP.setLevel(strNum(sysDeptP.getAncestors()));
                sysDept.setFullName(fullName);
                sysDept.setAncestors(pids);
            }else{
                //山东高速集团
                sysDept.setFullName(sysDept.getDeptName());
                sysDept.setAncestors("0");
            }
            String sqlupdate = "update sys_dept set ancestors=?, full_name=?, level=? where dept_id=?";
            int i = this.jdbcTemplate.update(sqlupdate,sysDept.getAncestors(),sysDept.getFullName(),sysDept.getLevel(), sysDept.getDeptId());
            log.info("修改" + (i == 1));
        }
        //修改
        Object result= TransforUtil.getResult(dto.getBimRequestId(),String.valueOf(sysDept.getDeptId()),insert,"uid",1);
        return result;


    }
    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public Object update(SysDeptDTO dto) {
        SyncSysDept sysDept =  ConvertUtils.sourceToTarget(dto, SyncSysDept.class);
        QueryWrapper<SyncSysDept> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dept_id",dto.getBimOrgId());
        //获取原信息
        SyncSysDept sysDept1 = sysDeptMapper.selectOne(queryWrapper);
        Result result=new Result();
        result.setBimRequestId(dto.getBimRequestId());
        if(TextUtil.isNull(sysDept1)){
            result.error("没有相关记录");
            return result;
        }
        String bimOrgId = dto.getBimOrgId();
        sysDept.setDeptId(bimOrgId);
        sysDept.setUpdateTime(new Date());
        sysDept.setUpdateBy(dto.getBimRemoteUser());
        String status = sysDept.getStatus();
        String fullName=sysDept1.getFullName();

        String name=sysDept.getDeptName();
        //原部门名称
        String oldName = sysDept1.getDeptName();
        //获取下级机构id
        List<String> updateIds = sysDeptMapper.getUpdateId(bimOrgId);
        List<String> updateIdstest = new ArrayList<>();
        //修改后的父级节点
        String pidNew="";
        if(sysDept.getParentId()!=null){
            pidNew= sysDept.getParentId().toString();
        }
        String pidsNew="";
        //修改节点的全路径
        String ownFullName="";
        if(updateIds!=null &&!updateIds.isEmpty()){
        //有下级节点

            if(TextUtil.isNotNull(pidNew)){
                //修改了父级机构
                sysDept.setParentId(pidNew);
                //取新父级节点pids
                String pids = this.getPids(pidNew);

                //修改了父级机构
                sysDept.setParentId(pidNew);
                //父节点的全路径
                String pfullName = sysDeptMapper.getPfullName(pidNew);
                if(TextUtil.isNotNull(name)){
                    pfullName=pfullName+"/"+name;
                }
                if(TextUtil.isNotNull(pids)){
                    //父节点pids不为空
                    pidsNew=pids+","+pidNew;
                    sysDept.setAncestors(pidsNew);
                }else{
                    //父节点pids为空，顶级机构
                    sysDept.setAncestors(pidsNew);
                }
                //修改本节点的数据 pids,pid和fullname
                String sqlUpdate="update sys_dept set ";
                if(TextUtil.isNotNull(pidsNew)){
                    sqlUpdate+=" ancestors='"+pidsNew+"',";
                }
                if(sysDept.getParentId()!=null){
                    sqlUpdate+="parent_id='"+sysDept.getParentId()+"',";
                }
                if(TextUtil.isNotNull(pfullName)){
                    sqlUpdate+="full_name='"+pfullName+"',";
                }
                if(TextUtil.isNotNull(status)){
                    sqlUpdate+="status = '"+status+"',";
                }
                sqlUpdate+="update_by ='"+sysDept.getUpdateBy()+"',update_time= now() where dept_id='"+bimOrgId + "'";

                this.jdbcTemplate.update(sqlUpdate);
                //修改下级单位的pids
                String replacePids = pids + ","+pidNew+",";
                String sql111=" update sys_dept set ";
                if(TextUtil.isNotNull(replacePids)){
                    sql111+="ancestors=replace(ancestors, split_part(ancestors, '"+bimOrgId+"', 1),'"+replacePids+"'),";
                }
                if(TextUtil.isNotNull(pfullName)){
                    sql111+="full_name=replace(full_name, split_part(full_name, dept_name, 1),'"+pfullName+"/'), ";
                }
                sql111+="update_by ='"+sysDept.getUpdateBy()+"',update_time= now() where dept_id in (";
                String   sql=sql111;
                //拼接下级单位id
                String sqlIds="";
                int size = updateIds.size();
                if(size>0){
                    //拼接下级单位id
                    for(int i=0;i<size;i++){
                      String value=  updateIds.get(i);
                        if(i==(size-1)){
                            sqlIds+= value+")";
                        }else{
                            sqlIds+=value+",";
                        }
                    }

                }
                if(TextUtil.isNotNull(pids)){
                    //更新子节点pids
                    this.jdbcTemplate.update(sql+sqlIds);
                } else{
                    String sqlroot=" update sys_dept set ancestors=replace(ancestors, split_part(ancestors, '"+bimOrgId+"', 1),'1,'),";

                    if(TextUtil.isNotNull(pfullName)){
                        sqlroot+="full_name=replace(full_name, split_part(full_name, dept_name, 1),'"+pfullName+"/') ";
                    }
                    sqlroot+="update_by ='"+sysDept.getUpdateBy()+"',update_time= now() where dept_id in (";
                    this.jdbcTemplate.update(sqlroot+sqlIds);
                }
            }else{
                //未修改父节点
                //有下级节点
                //修改子机构的全路径
                if(TextUtil.isNotNull(name)){
                    String sqlUpdateiii="update sys_dept  set full_name=REPLACE(full_name, '"+name+"', '"+oldName+"') where " +
                            "   dept_id in (" ;
                    //拼接下级单位id
                    String sqlIds="";
                    int size = updateIds.size();
                    if(size>0){
                        //拼接下级单位id
                        for(int i=0;i<size;i++){
                            String value = updateIds.get(i);
                            if(i==(size-1)){
                                sqlIds+= value+")";
                            }else{
                                sqlIds+=value+",";
                            }
                        }
                    }
                    this.jdbcTemplate.update(sqlUpdateiii+sqlIds);
                    //修改自身节点
                    String fullNameNew=fullName.replace(oldName,name);
                    sysDept.setFullName(fullNameNew);
                }
            }

        }else{
            //没有下级节点，只修改本身
            if(TextUtil.isNotNull(pidNew)){
                //修改了父级机构
                sysDept.setParentId(pidNew);
                String pids = this.getPids(pidNew);
                if(TextUtil.isNotNull(pids)){
                    pidsNew=pids+","+pidNew;
                    sysDept.setAncestors(pidsNew);
                }else{
                    //为空pid=1
                    if("1".equals(pidNew)){
                        pidsNew = "1";
                        sysDept.setAncestors(pidsNew);
                    }
                }
                QueryWrapper<SyncSysDept> queryWrapper1=new QueryWrapper<>();
                queryWrapper1.eq("dept_id",pidNew);
                SyncSysDept sysDeptNewP = sysDeptMapper.selectOne(queryWrapper1);
                String newfullName="";
                String oldFullName=fullName;
                if(sysDeptNewP!=null){
                    if(TextUtil.isNotNull(name)){
                        newfullName=sysDeptNewP.getFullName()+"/"+name;
                    }else{
                        newfullName=sysDeptNewP.getFullName()+"/"+oldName;
                    }
                }
                //修改自身节点
                sysDept.setFullName(newfullName);
            }else{
                //未修改父级机构，只修改了名称
                if(TextUtil.isNotNull(name)){
                    String fullNameNew=fullName.replace(oldName,name);
                    sysDept.setFullName(fullNameNew);
                }
            }
        }
     String sql=" update sys_dept set ";
      if(TextUtil.isNotNull(sysDept.getFullName())){
          sql+=" full_name='"+sysDept.getFullName()+"',";
      }
      if(TextUtil.isNotNull(sysDept.getAncestors())){
          sql+=" ancestors='"+sysDept.getAncestors()+"',";
      }
      if(TextUtil.isNotNull(sysDept.getDeptName())){
          sql+=" dept_name='"+sysDept.getDeptName()+"',";
      }
      if(sysDept.getParentId()!=null){
          sql+=" parent_id='"+sysDept.getParentId()+"',";
      }
        if(TextUtil.isNotNull(status)){
            sql+="status = '"+status+"',";
        }
        sql+= "update_by ='"+sysDept.getUpdateBy()+"',update_time= now() where dept_id='" + sysDept.getDeptId()+ "'";
        //将修改信息保存
        int i = this.jdbcTemplate.update(sql);
        if (i != 1) {
            result.error("修改失败");
        }
        return result;
    }

    @Override
    public Object delete(String id) {
        Result result=new Result<>();
        QueryWrapper<SyncSysDept> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dept_id",id);
        SyncSysDept sysDept = sysDeptMapper.selectOne(queryWrapper);
        if(sysDept==null){
            return result.error("机构不存在");
        }
        QueryWrapper<SyncSysDept> queryWrapperPid=new QueryWrapper<>();
        queryWrapperPid.eq("parent_id",id);
        List<SyncSysDept> sysDepts = sysDeptMapper.selectList(queryWrapperPid);

        if(!TextUtil.isNull(sysDepts)){
            String sql="update sys_dept set del_flag='2' where ancestors'" + id + "'";
            return result.error("此机构有下级节点，暂不能删除");
        }
        String sql="update sys_dept set del_flag='2' where dept_id='" + id + "'";
        int i= this.jdbcTemplate.update(sql);
        if (i != 1) {
            result.error("删除失败");
        }
        return result;
    }

    @Override
    public Object getAllDept(String random) {
        QueryWrapper<SyncSysDept> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("dept_id");
        List<Object> userIds = sysDeptMapper.selectObjs(queryWrapper);
        ResultUser resultUser=new ResultUser();
        resultUser.setBimRequestId(random);
        Object jsonObject;
        if(userIds!=null && userIds.size()!=0){
            resultUser.setUserIdList(userIds);
            jsonObject= TransforUtil.getJsonObject(resultUser,"orgIdList",2);
        }else{
            resultUser.setUserIdList(new ArrayList<>());
            jsonObject= TransforUtil.getJsonObject(resultUser,"orgIdList",2);
        }
        return BamboocloudFacade.encrypt(JSONUtil.toJsonStr(jsonObject), "123456", "AES");
    }

    @Override
    public Object getDeptById(String random,String uid) {
        QueryWrapper<SyncSysDept> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dept_id",uid);
        queryWrapper.select("dept_id as deptId","dept_name as deptName","parent_id as parentId","full_name as fullName");
        List<Map<String, Object>> sysUser = sysDeptMapper.selectMaps(queryWrapper);
        ResultUser resultUser=new ResultUser();
        resultUser.setBimRequestId(random);
        Object jsonObject;
        if(sysUser!=null && sysUser.size()!=0){
            resultUser.setUserIdList(sysUser);
            jsonObject = TransforUtil.getJsonObject(resultUser,"organization",1);//2
        }else{
            resultUser.setUserIdList(new ArrayList<>());
            jsonObject = TransforUtil.getJsonObject(resultUser,"organization",3);
        }
        return BamboocloudFacade.encrypt(JSONUtil.toJsonStr(jsonObject), "123456", "AES");
    }

    /**
     * @param id 机构id
     * @param isadd  是否是新增  1-新增  2-修改
     * @param pidsParam 修改时如果修改了pid,传入修改后的pids，其他情况下为空
     * @param name 机构名称，如果修改时修改了机构名称，传入其他情况下为空
     * @return
     */
    @Override
    public String getPidNames(String id,int isadd,String pidsParam,String name) {
        QueryWrapper<SyncSysDept> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dept_id",id);
        SyncSysDept sysDept = sysDeptMapper.selectOne(queryWrapper);
        StringBuilder pidName=new StringBuilder();
        if(!TextUtil.isNull(sysDept)){
            String pids="";
            if("1".equals(id)){
                //山东高速集团无父id
                pids="";
            }else{
                switch (isadd){
                    case 1:
                        pids=getPids(id);
                        break;
                    case 2:
                        if(TextUtil.isNotNull(pidsParam)){
                            //修改了pid,传入新修改的pids
                            pids=pidsParam;
                        }else{
                            pids=sysDept.getAncestors();
                        }
                        break;
                }
            }

            if(TextUtil.isNotNull(pids)){
                String[] split = pids.split(",");
                for(int i=0;i<split.length;i++){
                    queryWrapper.clear();
                    queryWrapper.eq("dept_id",split[i]);
                    SyncSysDept sysDept1 = sysDeptMapper.selectOne(queryWrapper);
                    if(!TextUtil.isNull(sysDept1)){
//                        if(i==split.length-1){
//                            pidName.append(sysDept1.getName());
//                        }else{
                            pidName.append(sysDept1.getDeptName()).append("/");
//                        }
                    }
                }
            }
            if("1".equals(id)){
                pidName.append(sysDept.getDeptName());
            }
            //不添加当前部门
            if(!TextUtil.isNull(name)){
                pidName.append(name);
            }else{
                pidName.append(sysDept.getDeptName());
            }

        }
        return pidName.toString();
    }

    @Override
    public String getPids(String pid) {
        String pids="";

        if(TextUtil.isNotNull(pid)){
            if("1".equals(pid)){
                //1没有父id，返回空
                pids="";
            }else{
                QueryWrapper<SyncSysDept> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("dept_id",pid);
                SyncSysDept sysDept = sysDeptMapper.selectOne(queryWrapper);
                if(sysDept!=null){
                    //查询父节点的pids,并返回
                    pids=sysDept.getAncestors();
                }
            }
        }
        return pids;
    }



    /**
     * 更新sys_dept表has_leaf pids full_name 字段
     *
     * @return
     */
    public String updateDeptFileld() {
        List<SyncSysDept> sysDeptList = this.list();
        String  id = "0";
        QueryWrapper<SyncSysDept> queryWrapper1 = new QueryWrapper<>();

        for (SyncSysDept dept : sysDeptList) {
            id = dept.getDeptId();
            queryWrapper1.eq("pid", id);
            //查询是否有下级机构，没有就是叶子结点 has_leaf 为1，否则为0
            queryWrapper1.clear();

            String pidNames = this.getPidNames(String.valueOf(id), 1, "", "");
            dept.setFullName(pidNames);
            dept.setAncestors(this.getPids(String.valueOf(id)));
            dept.setUpdateTime(new Date());
            this.updateById(dept);

        }
        return "success";
    }

    public String strNum(String str){
        char toCount = ',';
        int count = (int) str.chars().filter(ch -> ch == toCount).count();
        return String.valueOf(count);
    }
}
